package com.dooioo.pns.api.controller;

import com.dooioo.pns.business.service.AppInfoService;
import com.dooioo.pns.entity.model.AppInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * PackageName:com.dooioo.support.controller.api
 * Author: Jerry.hu
 * Create: Jerry.hu (2015-04-07 上午10:38)
 * Description:
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/api/app")
public class AppController {
	@Autowired
	private AppInfoService appInfoService;

	/**
	 * app 注册
	 * @param appName app名称
	 * @param appId app id
	 * @param appKey app key
	 * @return ResponseEntity
	 * @throws IOException
	 */
	@RequestMapping(value = "/register",method = RequestMethod.POST)
	protected @ResponseBody
	ResponseEntity<?> register(
			@RequestParam(value = "appName" ,required = true)String appName,
			@RequestParam(value = "appId" ,required = true)String appId,
			@RequestParam(value = "appKey" ,required = true)String appKey
	) throws IOException {
		Map<String,String>  mp = new HashMap<>();
		if(StringUtils.isBlank(appName)){
			mp.put("error","应用名称不许为空");
			return new ResponseEntity<>(mp, HttpStatus.BAD_REQUEST);
		}

		if(appInfoService.isExistsApp(appName)){
			mp.put("error","应用已经存在");
			return new ResponseEntity<>(mp, HttpStatus.BAD_REQUEST);
		}
		AppInfo appInfo = new AppInfo(appId,appKey,appName);
		if(appInfoService.insertAndReturnId(appInfo) > 0){
			return ResponseEntity.ok(appInfo);
		}else{
			mp.put("error","操作异常");
			return new ResponseEntity<>(mp, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}



}
